﻿Imports System.IO
Imports System.Text

Public Class Form1

    Public Const CaptionSaved As String = "MVDK Phisher"
    Public Const CaptionDirty As String = "MVDK Phisher*"

    Public Const NameXPath As String = "/html[1]/body[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[5]/td[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]"
    Public Const VehicleClassXPath As String = "/html[1]/body[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[9]/td[1]/table[1]/tbody[1]/tr[2]/td[2]/div[1]"
    Public Const MakesNameXPath As String = "/html[1]/body[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[9]/td[1]/table[1]/tbody[1]/tr[2]/td[3]"
    Public Const MakerClassXPath As String = "/html[1]/body[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[9]/td[1]/table[1]/tbody[1]/tr[2]/td[4]"
    Public Const RegDateXPath As String = "/html[1]/body[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[10]/td[1]/table[1]/tbody[1]/tr[2]/td[8]/div[1]"
    Public Const DeliveryDateXPath As String = "/html[1]/body[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[10]/td[1]/table[1]/tbody[1]/tr[2]/td[10]/div[1]"

    Public Shared Property Initialized() As Boolean = False
    Public Shared Property Processing() As Boolean = False
    Private Property NumberList() As List(Of String) = New List(Of String)
    Private Property CurrentIndex As Integer = 0
    Private WithEvents m_VehicleData As DataTable = Nothing
    Private m_RegNumber As String = String.Empty
    Private Property DataFile As String = String.Empty

    Public Sub New()
        InitializeComponent()
        m_VehicleData = New DataTable("Vehicle Data")
        With m_VehicleData.Columns
            .Add("REG NO")
            .Add("Owner Name")
            .Add("Vehicle Class")
            .Add("Makes Name")
            .Add("Makes Class")
            .Add("Registration Date")
            .Add("Delivery Date")
        End With
        Me.DataGridView1.DataSource = m_VehicleData
        Me.Text = CaptionSaved
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If My.MySettings.Default.Password = String.Empty Then
            Dim d As New ChangePassword()
            If DialogResult.OK <> d.ShowDialog(Me) Then
                End
            End If
        Else
            Dim d As New Login()
            If DialogResult.OK <> d.ShowDialog(Me) Then
                End
            End If
        End If

        Me.AxWebBrowser1.Navigate(My.Resources.MVKDPURL)
    End Sub

    Private Sub AxWebBrowser1_DocumentComplete(ByVal sender As Object, ByVal e As AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent) Handles AxWebBrowser1.DocumentComplete
        If Not Initialized Then
            Initialized = True
            LblStatus.Text = "Ready"
            Me.CmbCode.Enabled = True
            Me.CmbCode.Text = My.MySettings.Default.AreaCode
            Me.CmbSerial.Text = My.MySettings.Default.Serial
            Me.CmbSerial.Enabled = True
            Me.TxtNumber.Enabled = True
            Me.BtnProcess.Enabled = False
            Me.TxtNumber.Text = My.MySettings.Default.Number
        Else
            System.Windows.Forms.Application.DoEvents()
            System.Threading.Thread.Sleep(10)
            If Processing Then
                Try
                    Dim doc As mshtml.IHTMLDocument3 = CType(Me.AxWebBrowser1.Document, mshtml.IHTMLDocument3)
                    Dim doc2 As New HtmlAgilityPack.HtmlDocument()
                    doc2.LoadHtml(CType(doc, MSHTML.HTMLDocument).documentElement.outerHTML)

                    Dim nameNode As HtmlAgilityPack.HtmlNode = Nothing
                    Dim vehicleClassNode As HtmlAgilityPack.HtmlNode = Nothing
                    Dim makesNameNode As HtmlAgilityPack.HtmlNode = Nothing
                    Dim makesClassNode As HtmlAgilityPack.HtmlNode = Nothing
                    Dim regDateNode As HtmlAgilityPack.HtmlNode = Nothing
                    Dim delDateNode As HtmlAgilityPack.HtmlNode = Nothing

                    With doc2.DocumentNode
                        nameNode = .SelectSingleNode(NameXPath)
                        vehicleClassNode = .SelectSingleNode(VehicleClassXPath)
                        makesNameNode = .SelectSingleNode(MakesNameXPath)
                        makesClassNode = .SelectSingleNode(MakerClassXPath)
                        regDateNode = .SelectSingleNode(RegDateXPath)
                        delDateNode = .SelectSingleNode(DeliveryDateXPath)

                        Dim ownerName As String = String.Empty
                        Dim vehicleClass As String = String.Empty
                        Dim makesName As String = String.Empty
                        Dim makesClass As String = String.Empty
                        Dim regDate As String = String.Empty
                        Dim delDate As String = String.Empty

                        Dim recordFound As Boolean = False
                        If nameNode IsNot Nothing Then
                            ownerName = nameNode.InnerText.Trim()
                            recordFound = True
                        End If

                        If vehicleClassNode IsNot Nothing Then
                            vehicleClass = vehicleClassNode.InnerText.Trim()
                            recordFound = True
                        End If

                        If makesNameNode IsNot Nothing Then
                            makesName = makesNameNode.InnerText.Trim()
                            recordFound = True
                        End If

                        If makesClassNode IsNot Nothing Then
                            makesClass = makesClassNode.InnerText.Trim()
                            recordFound = True
                        End If

                        If regDateNode IsNot Nothing Then
                            regDate = regDateNode.InnerText.Trim()
                            recordFound = True
                        End If

                        If delDateNode IsNot Nothing Then
                            delDate = delDateNode.InnerText.Trim()
                            recordFound = True
                        End If
                        If recordFound Then
                            Dim row As DataRow = m_VehicleData.NewRow()
                            row.ItemArray = New Object() {m_RegNumber, ownerName, vehicleClass, makesName, makesClass, regDate, delDate}
                            m_VehicleData.Rows.Add(row)
                        End If
                    End With

                Catch ex As Exception
                    Trace.Write(ex)
                Finally
                    Me.CurrentIndex += 1
                    SendRequest(Me.CurrentIndex)
                End Try
            Else
                Me.NumberList.Clear()
                Me.CurrentIndex = 0
                Me.CmbCode.Enabled = True
                Me.CmbSerial.Enabled = True
                Me.TxtNumber.Enabled = True
                Me.BtnProcess.Enabled = True
                Me.LblStatus.Text = "Ready"
                System.Windows.Forms.Application.DoEvents()
            End If
        End If
    End Sub

    Private Sub AxWebBrowser1_ProgressChange(ByVal sender As Object, ByVal e As AxSHDocVw.DWebBrowserEvents2_ProgressChangeEvent) Handles AxWebBrowser1.ProgressChange
        If e.progress <> e.progressMax Then
            If Not Initialized Then
                LblStatus.Text = "Initializing phisher..."
            Else
                If Processing Then
                    LblStatus.Text = "Requesting data..."
                Else
                    LblStatus.Text = "Stop processing..."
                End If
            End If
        End If
    End Sub

    Private Sub LogHtmlNodeXPath(ByVal node As HtmlAgilityPack.HtmlNode)
        Trace.Write(node.Name & vbTab & node.XPath & vbCrLf & vbTab & node.InnerText.Trim().Replace(vbCrLf, " "))
        For Each childNode As HtmlAgilityPack.HtmlNode In node.ChildNodes
            LogHtmlNodeXPath(childNode)
        Next
    End Sub

    Private Sub TxtNumber_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TxtNumber.KeyDown
        If e.KeyCode = Keys.Enter Then
            If BtnProcess.Enabled Then
                BtnProcess_Click(BtnProcess, Nothing)
            End If
        End If
    End Sub

    Private Sub TxtNumber_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtNumber.TextChanged
        Dim number As UInt16 = 0
        Me.BtnProcess.Enabled = (UInt16.TryParse(Me.TxtNumber.Text.Trim(), number)) AndAlso (number > 0) AndAlso (Not Processing) AndAlso (Me.TxtNumber.Text.Length <= 4)
    End Sub

    Private Sub BtnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnProcess.Click
        Try
            Me.CmbCode.Enabled = False
            Me.TxtNumber.Enabled = False
            Me.BtnProcess.Enabled = False
            Me.CmbSerial.Enabled = False
            Me.Cursor = Cursors.WaitCursor
            Me.LblStatus.Text = "Generating number list..."
            Application.DoEvents()

            Me.NumberList.Clear()
            Me.CurrentIndex = 0

            Dim number As UInt16 = 0
            number = UInt16.Parse(TxtNumber.Text)
            My.MySettings.Default.Number = number.ToString()
            For index As Integer = number To 9999
                Dim text As String = String.Empty
                For f As Integer = 2 To 4
                    text = index.ToString("D" & f.ToString())
                    If Not Me.NumberList.Contains(text) Then
                        Me.NumberList.Add(text)
                    End If
                Next
            Next
            Processing = True
            BtnStop.Enabled = True
            SendRequest(CurrentIndex)
        Catch ex As Exception
            MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Finally
            Me.Cursor = Cursors.Default
            Me.LblStatus.Text = "Ready"
        End Try
    End Sub

    Private Sub SendRequest(ByVal index As Integer)
        Dim code As String = Me.CmbCode.Text.Trim()
        Dim number As String = String.Empty
        Dim serial As String = Me.CmbSerial.Text.Trim()
        If index < NumberList.Count Then
            number = NumberList(index)
        End If
        Dim doc As MSHTML.HTMLDocument = Nothing
        doc = CType(Me.AxWebBrowser1.Document, MSHTML.HTMLDocument)
        Dim form1 As MSHTML.IHTMLFormElement
        form1 = CType(doc.getElementById("form1"), mshtml.IHTMLFormElement)
        Dim regNumber As String = String.Empty
        regNumber = "KL-" & code & "-" & serial & "-" & number
        m_RegNumber = regNumber
        CType(doc.getElementsByName("regfield")(0), MSHTML.HTMLInputElement).value = regNumber
        CType(doc.getElementsByName("Submit")(0), MSHTML.IHTMLElement).click()
        Me.TxtNumber.Text = number
        System.Windows.Forms.Application.DoEvents()
    End Sub

    Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click
        Processing = False
        Me.BtnStop.Enabled = False
        System.Windows.Forms.Application.DoEvents()
    End Sub

    Private Sub m_VehicleData_RowDeleted(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) Handles m_VehicleData.RowDeleted
        BtnSaveAs.Enabled = m_VehicleData.Rows.Count > 0
        BtnSave.Enabled = m_VehicleData.Rows.Count > 0
        Me.Text = CaptionDirty
    End Sub

    Private Sub m_VehicleData_TableNewRow(ByVal sender As Object, ByVal e As System.Data.DataTableNewRowEventArgs) Handles m_VehicleData.TableNewRow
        BtnSaveAs.Enabled = m_VehicleData.Rows.Count > 0
        BtnSave.Enabled = m_VehicleData.Rows.Count > 0
        Me.Text = CaptionDirty
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Dim changes As DataTable = Nothing
        changes = m_VehicleData.GetChanges(System.Data.DataRowState.Added)
        If Not changes Is Nothing Then

        End If
    End Sub

    Private Sub SaveAs()
        Dim sfd As New SaveFileDialog()
        sfd.Filter = "Comma Separated Values|*.csv"
        sfd.FileName = String.Empty
        If DialogResult.OK = sfd.ShowDialog() Then
            Me.DataFile = sfd.FileName
            Save(sfd.FileName)
        End If
    End Sub

    Private Sub Save(ByVal fileName As String)
        Dim fstream As New FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)
        Try
            Dim columnHeader As String = String.Empty
            For Each column As DataColumn In m_VehicleData.Columns
                columnHeader &= column.ColumnName & ","
            Next
            columnHeader = columnHeader.Trim(",".ToCharArray())
            columnHeader &= vbCrLf

            Dim buffer As Byte() = Encoding.UTF8.GetBytes(columnHeader)
            fstream.Write(buffer, 0, buffer.Length)
            fstream.Flush()
            For Each row As DataRow In m_VehicleData.Rows
                Dim rowLine As String = String.Empty
                Dim items As Object() = row.ItemArray
                For Each item As Object In items
                    Dim data As String = Convert.ToString(item)
                    data = data.Replace("""", """""")
                    data = """" & data & """"
                    rowLine &= data & ","
                Next
                rowLine = rowLine.Trim(",".ToCharArray())
                rowLine &= vbCrLf
                buffer = Encoding.Default.GetBytes(rowLine)
                fstream.Write(buffer, 0, buffer.Length)
                fstream.Flush()
            Next
            m_VehicleData.AcceptChanges()
            Me.Text = CaptionSaved
        Catch
            Throw
        Finally
            fstream.Close()
            fstream.Dispose()
            fstream = Nothing
        End Try
    End Sub

    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        If String.Compare(Me.DataFile, String.Empty) = 0 Then
            Me.SaveAs()
        Else
            Me.Save(Me.DataFile)
        End If
    End Sub

    Private Sub BtnSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveAs.Click
        Me.SaveAs()
    End Sub

    Private Sub CmbCode_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmbCode.SelectedIndexChanged
        My.MySettings.Default.AreaCode = Me.CmbCode.Text.Trim()
    End Sub

    Private Sub CmbSerial_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmbSerial.SelectedIndexChanged
        My.MySettings.Default.Serial = Me.CmbSerial.Text.Trim()
    End Sub

    Private Sub ResetSettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResetSettingsToolStripMenuItem.Click
        If DialogResult.Yes = MessageBox.Show("Reset your current settings?", Me.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) Then
            My.MySettings.Default.AreaCode = "01"
            My.MySettings.Default.Serial = "A"
            My.MySettings.Default.Number = String.Empty
            My.MySettings.Default.Password = String.Empty
            MessageBox.Show("Your settings has been reset. Restart your application to apply new settings.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End If
    End Sub

    Private Sub ChangePasswordToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangePasswordToolStripMenuItem.Click
        If (New ChangePassword()).ShowDialog() = DialogResult.OK Then
            MessageBox.Show("Your password has been reset.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub ToolStripSplitButton1_ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripSplitButton1.ButtonClick
        If (New ChangePassword()).ShowDialog() = DialogResult.OK Then
            MessageBox.Show("Your password has been reset.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
End Class
